package com.laicunba.ext.web.controller.console.sys;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Map;

import org.json.simple.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.laicunba.ext.web.controller.BaseController;
import com.laicunba.pojo.RegistryDO;
import com.laicunba.service.RegistryService;
import com.laicunba.util.DateUtil;
import com.laicunba.util.StringUtil;

@Controller
@RequestMapping(value = "/console/ext/sys")
public class BannerPlanController extends BaseController {
	@Autowired
	private RegistryService registryService;

	private static SimpleDateFormat FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	@ResponseBody
	@RequestMapping(value = "/list_banner_plan.htm")
	public String listBannerPlan() {
		Map<String, String> bannerMap = registryService.likeKey("banner.plan.");
		return toJsonObject(bannerMap);
	}

	@SuppressWarnings("unchecked")
	@ResponseBody
	@RequestMapping(value = "/banner_plan_save.htm")
	public String bannerPlanSave(String id, String pic, String href, String begin_time, String end_time) {
		JSONObject json = new JSONObject();
		if (StringUtil.isEmpty(id) || !id.startsWith("banner.plan.")) {
			json.put("code", "ID_ERROR");
			return json.toJSONString();
		}


		try { 
			Object obj = StringUtil.isNotEmpty(begin_time)?FORMAT.parse(begin_time):null;
			obj = StringUtil.isNotEmpty(end_time)?FORMAT.parse(end_time):null;
		} catch (ParseException e) {
			json.put("code", "PARAM_TIME_ERROR");
			return json.toJSONString();
		}

		JSONObject valJson = new JSONObject();
		valJson.put("pic", pic);
		valJson.put("href", href);
		valJson.put("begin_time", begin_time);
		valJson.put("end_time", end_time);
		RegistryDO registryDO = registryService.get(RegistryDO.class, id);
		json.put("code", registryDO == null ? registryService.create(id, valJson.toJSONString()) : registryService.update(id, valJson.toJSONString()));

		return json.toJSONString();
	}
}
